package top.jingles.tools.deploytool.entity;

import java.io.File;
import java.util.regex.Pattern;

import lombok.Data;

@Data
public class JarInfo {
    public static final Pattern DATE_PATTERN = Pattern.compile("-[\\d]{8}\\.[\\d]{6}-");

    File file;
    JarType type;
    String classifier;

    public enum JarType {
        normal,
        javadoc,
        sources,
        tests,
        other
    }

    public JarInfo(File f, String prefix) {
        file = f;
        type = getJarType(f.getName());
        guessClassifierAndType(f.getName(), prefix);
    }

    static JarType getJarType(String filename) {
        return JarType.normal;
    }

    boolean guessClassifierAndType(String filename, String prefix) {
        if (DATE_PATTERN.matcher(filename).find()) {
            // skip
            // 忽略日期快照版本，如 xxx-mySql-2.2.6-20170714.095105-1.jar
            type = JarType.other;
            return false;
        } else if (filename.endsWith("-javadoc.jar")) {
            classifier = filename.substring(prefix.length(), filename.length() - "-javadoc.jar".length());
            type = JarType.javadoc;
        } else if (filename.endsWith("-sources.jar")) {
            classifier = filename.substring(prefix.length(), filename.length() - "-sources.jar".length());
            type = JarType.sources;
        } else if (filename.endsWith("-tests.jar")) {
            classifier = filename.substring(prefix.length(), filename.length() - "-tests.jar".length());
            type = JarType.tests;
        } else if (filename.endsWith(".jar")) {
            classifier = filename.substring(prefix.length(), filename.length() - ".jar".length());
            type = JarType.normal;
        } else {
            type = JarType.other;
            return false;
        }
        if (classifier.length() > 0) {
            classifier = classifier.substring(1);
        }
        return true;
    }
}